iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
Vue.js

Vue 新手學習紀錄系列 第 11

Day 11|Composition API 入門

  • 分享至 

  • xImage
  •  

昨天寫了 Vue 的 Options API,它用 data、methods、computed 來分門別類。這種寫法清楚、直觀,但在會有「邏輯分散」的問題。於是,Vue 3 推出了新的寫法 —— Composition API。它最大的特色就是:邏輯集中在一起,彈性更高,能抽出共用函式。

Composition API 架構

<script setup>
import { ref, computed } from 'vue'

const count = ref(0)
const double = computed(() => count.value * 2)
function increment() {
  count.value++
}
</script>

<template>
  <p>{{ count }} → {{ double }}</p>
  <button @click="increment">增加</button>
</template>
  • ref:建立單一響應式數值
  • reactive:建立物件或陣列的響應式狀態
  • computed:計算屬性
  • watch:監聽狀態變化

對比 Option API

<script>
export default {
  data() {
    return { count: 0 }
  },
  methods: {
    increment() { this.count++ }
  },
  computed: {
    double() { return this.count * 2 }
  }
}
</script>

目前在這個系統中的應用

  • 搜尋功能
  • 詳細資料面板
  • 分享經驗的表單

Option API 和 Composition API 小小比較

Options API 特徵

  • 結構清楚
  • 舊專案常見
  • 邏輯分散:功能被拆到不同區塊
  • 重複使用較困難:mixin 可讀性差

Composition API 特徵

  • 邏輯集中:相關狀態與方法放在一起
  • 更容易重複使用:可抽成 composable 函式

感覺明天可以來看一下 composable 函式的部分


上一篇
Day 10|Options API 入門
下一篇
Day 12 | Composable 函式: 模組化程式邏輯
系列文
Vue 新手學習紀錄12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言